<template>
  <div class="f_div">
    <div class="t_div">
      设置 / 车辆管理 / <a href="#">{{ name }}</a>
    </div>
    <el-container>
      <el-header class="header"
        ><div class="h_div">
          <div class="h_in_vid">基础信息</div>
        </div></el-header
      >
      <el-main class="main">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车牌号" prop="vc_phone">
                <el-input
                  v-model="ruleForm.vc_phone"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车型" prop="vc_model">
                <el-select
                  v-model="ruleForm.vc_model"
                  placeholder="请选择"
                  style="width: 700px"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in model"
                    :key="item.dict_code"
                    :label="item.dict_label"
                    :value="item.dict_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车长" prop="vc_length">
                <el-select
                  v-model="ruleForm.vc_length"
                  placeholder="请选择"
                  style="width: 700px"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in length"
                    :key="item.dict_code"
                    :label="item.dict_label"
                    :value="item.dict_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车辆颜色" prop="vc_color">
                <el-input
                  v-model="ruleForm.vc_color"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆品牌" prop="vc_brand">
                <el-input
                  v-model="ruleForm.vc_brand"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核定载客" prop="vc_pas_cap">
                <el-input
                  v-model="ruleForm.vc_pas_cap"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="核载体积（m³）" prop="vc_vol_cap">
                <el-input
                  v-model="ruleForm.vc_vol_cap"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="核载重量（kg）" prop="vc_wt_cap">
                <el-input
                  v-model="ruleForm.vc_wt_cap"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出场日期" prop="vc_rel_date">
                <el-date-picker
                  v-model="ruleForm.vc_rel_date"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  style="width: 700px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车辆年限" prop="vc_veh_age">
                <el-input
                  v-model="ruleForm.vc_veh_age"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="制造商" prop="vc_manu">
                <el-input v-model="ruleForm.vc_manu" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车主" prop="dv_id">
                <el-select
                  v-model="ruleForm.dv_id"
                  placeholder="请选择"
                  style="width: 700px"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in drivers"
                    :key="item.dv_id"
                    :label="item.dv_name"
                    :value="item.dv_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="状态">
                <el-switch v-model="ruleForm.vc_status" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="车辆图片" prop="vc_photo">
                <el-upload
                  action="http://localhost:5261/api/Company/Upload"
                  list-type="picture-card"
                  :auto-upload="true"
                  v-model:file-list="rulelist"
                  :limit="9"
                  ref="upload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  accept=".jpg,.png"
                  :on-exceed="handleExceed"
                  :multiple="true"
                >
                  <el-icon><Plus /></el-icon>
                  <template #file="{ file }">
                    <div>
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <el-icon><zoom-in /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleDownload(file)"
                        >
                          <el-icon><Download /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleRemove(file)"
                        >
                          <el-icon><Delete /></el-icon>
                        </span>
                      </span>
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              <div
                style="
                  color: #cccccc;
                  font-size: 14px;
                  text-align: left;
                  margin-left: 130px;
                "
              >
                最多上传9张，单张图片大小不超过2M,并只能给.jpg和.png格式
              </div>
              <el-dialog v-model="dialogVisible">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="max-width: 100%; height: auto"
                />
              </el-dialog>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="备注信息" prop="vc_remarks">
                <el-input
                  v-model="ruleForm.vc_remarks"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item>
                <el-button type="primary" style="width: 80px" @click="onSubmit"
                  >保存</el-button
                >
                <el-button style="width: 80px" @click="cancel">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import $http from "@/axios/base";
import { getRandomString } from "@/randomString/random.js";
import { ElMessage } from "element-plus";
export default {
  name: "app",
  setup() {
    const route = useRoute();
    const router = useRouter();
    const name = ref("");
    const ruleFormRef = ref(null);
    const ruleForm = reactive({
      vc_id: 0, //车辆id
      vc_phone: "", //车牌号
      vc_model: "", //车型
      vc_length: "", //车长
      vc_color: "", //车辆颜色
      vc_brand: "", //车辆品牌
      vc_pas_cap: 0, //核定载客
      vc_vol_cap: "", //核载体积
      vc_wt_cap: "", //核载重量
      vc_rel_date: "", //出场日期
      vc_veh_age: "", //车辆年限
      vc_manu: "", //制造商
      dv_id: "", //车主id
      vc_status: true, //车辆状态
      vc_photo: "", //车辆图片
      vc_remarks: "", //备注信息
      create_by: sessionStorage.getItem("empname"), //创建人
      create_time: new Date().toISOString().slice(0, 10).toString(), //创建时间
      update_by: "", //修改人
      update_time: "", //修改日期
      is_del: 0, //是否删除
    });
    const rules = ref({
      vc_phone: [
        { required: true, message: "请输入车牌号", trigger: "blur" },
        { min: 7, max: 8, message: "车牌号长度为7-8位", trigger: "blur" },
      ],
      vc_model: [{ required: true, message: "请选择车型", trigger: "change" }],
      vc_length: [{ required: true, message: "请选择车长", trigger: "change" }],
      vc_color: [
        { required: true, message: "请输入车辆颜色", trigger: "blur" },
      ],
      vc_brand: [
        { required: true, message: "请输入车辆品牌", trigger: "blur" },
      ],
      vc_pas_cap: [
        { required: true, message: "请输入核定载客人数", trigger: "blur" },
        {
          pattern: /^\d+$/,
          message: "核定载客人数必须为数字",
          trigger: "blur",
        },
      ],
      vc_vol_cap: [
        { required: true, message: "请输入核载体积", trigger: "blur" },
        {
          pattern: /^\d+(\.\d{1,2})?$/,
          message: "核载体积必须为数字，最多保留两位小数",
          trigger: "blur",
        },
      ],
      vc_wt_cap: [
        { required: true, message: "请输入核载重量", trigger: "blur" },
        {
          pattern: /^\d+(\.\d{1,2})?$/,
          message: "核载体积必须为数字，最多保留两位小数",
          trigger: "blur",
        },
      ],
      vc_rel_date: [
        { required: true, message: "请选择出场日期", trigger: "change" },
      ],
      vc_veh_age: [
        { required: true, message: "请输入车辆年限", trigger: "blur" },
      ],
      vc_manu: [{ required: true, message: "请输入制造商", trigger: "blur" }],
      dv_id: [{ required: true, message: "请选择车主", trigger: "change" }],
      vc_photo: [
        { required: true, message: "请上传驾驶证照片", trigger: "change" },
      ],
      vc_remarks: [
        { max: 200, message: "备注信息最多200个字符", trigger: "blur" },
      ],
    });
    const rulelist = ref([]);
    const upload = ref(null);
    const disabled = ref(false);
    const dialogVisible = ref(false);
    const dialogImageUrl = ref("");
    const model = ref();
    const length = ref();
    const drivers = ref();

    const getType = (value) => {
      $http
        .get("http://localhost:5261/api/Sys_Dict_data/Get_Dict_Types", {
          params: {
            Dict_name: value,
          },
        })
        .then((res) => {
          if (value == "车型") model.value = res;
          if (value == "车长") length.value = res;
        })
        .catch((err) => console.log(err));
    };

    //上传成功回调函数
    const handleUploadSuccess = (response, file, fileList) => {
      // 处理上传成功的逻辑，如显示成功消息或更新UI
      console.log("上传成功", response, file, fileList);
      // rulelist.url = response.result.url;
      // if (ruleForm.vc_photo == undefined)
      //   ruleForm.vc_photo = response.result.url + ",";
      // else ruleForm.vc_photo += response.result.url + ",";
      console.log(ruleForm.vc_photo);
    };

    //上传失败回调函数
    const handleUploadError = (error, file, fileList) => {
      // 处理上传失败的逻辑，如显示错误消息或更新UI
      console.error("上传失败", error, file, fileList);
      ElMessage.error("上传失败，文件大小或类型不符合要求");
    };

    //提交
    const onSubmit = () => {
      if (rulelist.value == undefined) {
        ElMessage.warning("请上传至少一张图片");
        return;
      }
      //图片上传
      ruleForm.vc_photo = "";
      rulelist.value.forEach((item) => {
        if (item.response != undefined)
          ruleForm.vc_photo += item.response.result.url + ",";
        else ruleForm.vc_photo += item.url + ",";
      });
      ruleForm.vc_photo = ruleForm.vc_photo.slice(0, -1);
      console.log(ruleForm.vc_photo);
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          //状态赋值
          if (ruleForm.vc_status == true) ruleForm.vc_status = 0;
          else if (ruleForm.vc_status == false) ruleForm.vc_status = 1;
          //模型和长度
          ruleForm.vc_model = ruleForm.vc_model.toString();
          ruleForm.vc_length = ruleForm.vc_length.toString();
          //判断车辆id是否为空
          if (ruleForm.vc_id == 0) {
            $http
              .post(
                `http://localhost:5261/api/Vehicles/AddVehicles/register`,
                ruleForm
              )
              .then((res) => {
                if (res) {
                  ElMessage.success("添加成功！！！");
                  setTimeout(() => {
                    router.push("/Vehicles");
                  }, 500);
                }
              })
              .catch((err) => console.log(err));
          } else {
            ruleForm.update_by = sessionStorage.getItem("empname");
            ruleForm.update_time = new Date()
              .toISOString()
              .slice(0, 10)
              .toString();
            $http
              .put(
                `http://localhost:5261/api/Vehicles/UpdVehicles/register`,
                ruleForm
              )
              .then((res) => {
                if (res) {
                  ElMessage.success("修改成功！！！");
                  setTimeout(() => {
                    router.push("/Vehicles");
                  }, 500);
                }
              })
              .catch((err) => console.log(err));
          }
        }else{
          //验证没有通过
          ElMessage.warning("请填写完整数据！！！");
        }
      });
    };

    //保存
    const handleDownload = (file) => {
      var now = new Date();

      // 获取年、月、日、时、分、秒
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // 注意月份是从 0 开始的
      var day = now.getDate();
      var imageUrl = file.url;
      var link = document.createElement("a");
      link.href = imageUrl;
      link.download =
        "七尾-" + year + month + day + getRandomString(8) + ".jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    //打开图片
    const handlePictureCardPreview = (file) => {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    };

    //删除
    const handleRemove = (file) => {
      // ruleForm.vc_photo = "";
      const index = rulelist.value.findIndex((e) => e.name === file.name);
      if (index !== -1) {
        rulelist.value.splice(index, 1);
      }
    };

    //取消
    const cancel = () => {
      router.push("Vehicles");
    };

    const getCount = () => {
      $http
        .get("http://localhost:5261/api/Drivers/GetCount")
        .then((res) => {
          getDrivers(res);
        })
        .catch((err) => console.log(err));
    };

    const getDrivers = (value) => {
      $http
        .get("http://localhost:5261/api/Drivers/GetDrivers", {
          params: {
            currentPage: 1,
            pageSize: value,
          },
        })
        .then((res) => {
          drivers.value = res;
        })
        .catch((err) => console.log(err));
    };

    const handleExceed = () => {
      ElMessage.warning("图片数量超出数量！");
    };

    const show = (id) => {
      $http
        .get(`http://localhost:5261/api/Vehicles/GetById/${id}`)
        .then((res) => {
          ruleForm.vc_id = res.vc_id;
          ruleForm.vc_phone = res.vc_phone;
          ruleForm.vc_model = parseInt(res.vc_model);
          ruleForm.vc_length = parseInt(res.vc_length);
          ruleForm.vc_color = res.vc_color;
          ruleForm.vc_brand = res.vc_brand;
          ruleForm.vc_pas_cap = res.vc_pas_cap;
          ruleForm.vc_vol_cap = res.vc_vol_cap;
          ruleForm.vc_wt_cap = res.vc_wt_cap;
          ruleForm.vc_rel_date = res.vc_rel_date;
          ruleForm.vc_veh_age = res.vc_veh_age;
          ruleForm.vc_manu = res.vc_manu;
          ruleForm.dv_id = res.dv_id;
          if (res.vc_status == 0) ruleForm.vc_status = true;
          else if (res.vc_status == 1) ruleForm.vc_status = false;
          ruleForm.vc_photo = res.vc_photo;
          let arr = res.vc_photo.split(",");
          arr.forEach((item, index) => {
            rulelist.value.push({ url: item, name: index });
          });
          ruleForm.vc_remarks = res.vc_remarks;
          ruleForm.create_by = res.create_by;
          ruleForm.create_time = res.create_time;
          console.log(arr);
        })
        .catch((err) => console.log(err));
    };

    onMounted(() => {
      name.value = route.query.name;
      var id = route.query.id;
      getType("车长");
      getCount();
      getType("车型");
      if (id > 0) show(id);
    });

    return {
      name,
      show,
      rules,
      model,
      length,
      upload,
      getType,
      drivers,
      disabled,
      ruleForm,
      rulelist,
      ruleFormRef,
      handleExceed,
      handleRemove,
      dialogVisible,
      dialogImageUrl,
      handleDownload,
      handleUploadError,
      handleUploadSuccess,
      handlePictureCardPreview,
      onSubmit,
      cancel,
    };
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 50px;
  background-color: #006eff;
}

.el-radio-group {
  margin-right: 12px;
}
.t_div {
  margin-bottom: 20px;
  text-align: left;
  font-size: 14px;
  color: #b3b4b6;
}
a {
  text-decoration: none;
}
.f_div {
  padding: 0px 50px;
}
.h_div {
  border-bottom: 1px solid #f2f2f2;
  height: 39px;
}
.h_in_vid {
  width: 100px;
  height: 20px;
  margin-top: 20px;
  border-left: 5px solid #006eff;
}
.header {
  background-color: #ffffff;
  border-radius: 10px 10px 0px 0px;
}
.main {
  background-color: #ffffff;
  border-radius: 0px 0px 10px 10px;
  height: 750px;
}
.form_content {
  margin-left: 50px;
}
</style>